package com.example.ktpermissionx.ui.main

import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.ktpermissionx.FooterAdapter
import com.example.ktpermissionx.R
import com.example.ktpermissionx.RepoAdapter
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class Paging3Fragment : Fragment() {
    private val repoAdapter = RepoAdapter()
    companion object {
        fun newInstance() = Paging3Fragment()
    }

    private lateinit var viewModel: MainViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(R.layout.main_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        // TODO: Use the ViewModel
        val recyclerView = view?.findViewById<RecyclerView>(R.id.recycler_view)
        val progressBar = view?.findViewById<ProgressBar>(R.id.progress_bar)
        if (recyclerView != null) {
            recyclerView.layoutManager = LinearLayoutManager(context)
        }
        if (recyclerView != null) {
            recyclerView.adapter = repoAdapter.withLoadStateFooter(FooterAdapter { repoAdapter.retry() })
        }
        lifecycleScope.launch {
            viewModel.getPagingData().collect { pagingData ->
                repoAdapter.submitData(pagingData)
            }
        }
        repoAdapter.addLoadStateListener {
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    progressBar!!.visibility = View.INVISIBLE
                    recyclerView!!.visibility = View.VISIBLE
                }
                is LoadState.Loading -> {
                    progressBar!!.visibility = View.VISIBLE
                    recyclerView!!.visibility = View.INVISIBLE
                }
                is LoadState.Error -> {
                    val state = it.refresh as LoadState.Error
                    progressBar!!.visibility = View.INVISIBLE
                    Toast.makeText(context, "Load Error: ${state.error.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

}